import argparse
from pprint import pprint
import exifread
from geopy.geocoders import Nominatim


def dms_to_decimal(degrees, minutes, seconds, ref):
    decimal = degrees + minutes / 60 + seconds / 3600
    if ref in ["S", "W"]:
        decimal = -decimal
    return decimal


def get_location_geopy(latitude, longitude):
    geolocator = Nominatim(user_agent="geoapi")
    location = geolocator.reverse(
        f"{float(latitude)}, {float(longitude)}", language="zh"
    )
    return location.address if location else "未知位置"


def get_image_metadata(file_path: str):
    time = ""
    positions = {}

    with open(file_path, "rb") as file_handle:
        # Return Exif tags
        tags = exifread.process_file(file_handle)
        for tag, value in tags.items():
            if tag == "GPS GPSLatitude":
                value = value.values
                direction = tags.get("GPS GPSLatitudeRef").values

                latitude = dms_to_decimal(value[0], value[1], value[2], direction)
                positions["latitude"] = latitude

            if tag == "GPS GPSLongitude":
                value = value.values
                direction = tags.get("GPS GPSLongitudeRef").values
                longitude = dms_to_decimal(value[0], value[1], value[2], direction)
                positions["longitude"] = longitude

            if tag.__contains__("DateTime"):
                time = value.values

    positions["time"] = time
    positions["address"] = get_location_geopy(
        positions["latitude"], positions["longitude"]
    )
    pprint(f"Time : {positions['time']}\n Address : {positions['address']}")


def main():
    parser = argparse.ArgumentParser(description="Process image metadata from path.")
    parser.add_argument("image_path", metavar="file_path", type=str, help="file path")
    args = parser.parse_args()
    if not args.image_path:
        parser.print_help()
        exit(1)
    get_image_metadata(args.image_path)


if __name__ == "__main__":
    main()
    a = 2134
